package com.tianji.learning;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class MyDelayedTask implements Delayed {

    // 任务的执行时间
    private int executeTime = 0;
    private String name;

    public MyDelayedTask(int delay, String name) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, delay);
        this.executeTime = (int) (calendar.getTimeInMillis() / 1000);
        this.name = name;
    }

    /**
     * 元素在队列中的时间
     */
    @Override
    public long getDelay(TimeUnit unit) {
        Calendar calendar = Calendar.getInstance();
        return executeTime - (calendar.getTimeInMillis() / 1000);
    }

    /**
     * 元素排序
     */
    @Override
    public int compareTo(Delayed o) {
        long val = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        return val == 0 ? 0 : (val < 0 ? -1 : 1);
    }

    @Override
    public String toString() {
        return "MyDelayedTask{" +
                "executeTime=" + executeTime +
                ", name='" + name + '\'' +
                '}';
    }

    public static void main(String[] args) {
        DelayQueue<MyDelayedTask> queue = new DelayQueue<>();
        queue.add(new MyDelayedTask(10, "李四"));
        queue.add(new MyDelayedTask(5, "张三"));
        queue.add(new MyDelayedTask(15, "王五"));
        System.out.println(new Date() + " start consume");
        while (queue.size() != 0) {
            MyDelayedTask delayedTask = queue.poll();//弹出元素，poll是非阻塞的方法
            if (delayedTask != null) {
                System.out.println(new Date() + " consume task" + delayedTask);
            } else {
                System.out.println("元素为空");
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}
